var db = require('./db');
var mongodb = new db();
var ObjectID = require("mongodb").ObjectID;
var ifmIndex = require('./ifmIndex.js');
var cfm  =require('./cfm.js')
var logger = require('./logger.js');

var relationList = ['is-a','deserve','initiate','target', 'dealwith','generate','impact','jeopardize'];

//基本实现
exports.create= function createCD(ifmData,callback){
    mongodb.getCollection('ifm',function(collection){
        collection.findOne({user:ifmData.user, ccd_id:ifmData.ccd_id}, function(err, doc) {
            if(err != null){
                return callback(err, doc);
            }
            if(doc != null){
                err = "already Exist";
                return callback(err, doc);
            }
            collection.insert(ifmData, {safe: true}, function(err, doc) {
                logger.generateLogData('INFO','ifm','insert',ifmData);
                ifmIndex.update(doc[0],function(err2,doc2){
                    return callback(err, doc);
                });
            });
        });
    });
};

exports.addastest = function addastest(filter,callback){
    mongodb.getCollection('ifm',function(collection){
        collection.update(filter[0],{"$set" : filter[1]}, {safe: true}, function(err, doc) {
            logger.generateLogData('INFO','ifm','update',[filter[0],{"$set" : filter[1]}]);
            return callback();
        });
    });
}

//get正常
exports.get = function get(collectionName,filter,callback){
    mongodb.getCollection('ifm_'+collectionName,function(collection){
        collection.find(filter).toArray(function(err,doc){
             if(err != null){
                return callback(err, doc);
             }
             if(doc === null){
                 err = "not Exist";
                 return callback(err, doc,collectionName);
             }
             //console.log(doc);
             return callback(err, doc,collectionName);
        });
    });
};

//测试通过
exports.remove = function removeIfm(collectionName,filter,callback){
    mongodb.getCollection('ifm_'+collectionName,function(collection){
        collection.find(filter).toArray(function(err,doc){
            //logger.generateLogData('INFO','ifm','remove',filter);
            if(doc.length === 0)  callback(err,doc);
            for(var i=0;i<doc.length;i++){
                console.log(doc[i]._id)
                collection.remove({_id:doc[i]._id},function(err){
                    if (err) console.warn(err.message);
                    else {
                        console.log('ifm successfully removed');
                    }
                });
                var filter = [
                    {_id:doc[i].cfm_id},
                    doc[i]
                ]
                IfmExchangeToCfm('remove',collectionName,filter);
            }
            return callback(err,doc);
        })
    });
};

//
exports.copy= function copyElem(id,element,callback){
    console.log(element);
    mongodb.getCollection('ifm',function(collection){
        collection.update(id,{"$set":element},{safe:true},function(err,count) {
            logger.generateLogData('INFO','ifm','update',[id,{"$set":element}]);
            if (err) console.warn(err.message);
            else console.log('ifm successfully copyed');
            return callback(err,count);
        });
    });
};


exports.add= function addElem(collectionName, filter,callback){
    mongodb.getCollection('ifm_'+collectionName,function(collection){
        collection.insert(filter, {safe: true}, function(err, doc) {
            //logger.generateLogData('INFO','ifm_'+collectionName,'insert',filter);
            //IfmExchangeToCfm('add',collectionName,filter);
            return callback(err, doc);
        });
    });
};

exports.relationAdd = function relationAdd(collectionName, filter,callback){
    mongodb.getCollection('ifm_'+collectionName,function(collection){
        collection.update(filter[0],{"$set":filter[1]},{safe:true}, function(err, count) {
            return callback(err, count);
        });
    });
};

exports.relationRemove = function relationAdd(collectionName, filter,callback){
    mongodb.getCollection('ifm_'+collectionName,function(collection){
        collection.update(filter[0],{"$unset":filter[1]},{safe:true}, function(err, count) {
            return callback(err, count);
        });
    });
};
//
exports.delete= function deleteElem(filter,callback){
    mongodb.getCollection('ifm',function(collection){
        collection.update(filter[0],{"$unset":filter[1]},{safe:true},function(err,count) {
            logger.generateLogData('INFO','ifm','update',[filter[0],{"$unset":filter[1]}]);
            if (err) console.warn(err.message);
            else console.log('successfully deleted');
            return callback(err,count);
        });
    });
};

exports.revise = function revise(filter,callback){
    filter[1] = '{"'+filter[1]+'._nor":1';

    mongodb.getCollection('ifm',function(collection){
        collection.update(filter[0],{"$set":filter},{safe:true},function(err) {
            logger.generateLogData('INFO','ifm','update',[filter[0],{"$set":filter[1]}]);
            if (err) console.warn(err.message);
            else console.log('ifm successfully revised');
        });
    });
};

//不完整的信息
exports.getInfo = function getInfo(type,stateArray){
    var info= {
        id : ObjectID(stateArray._id)
    }
    switch(type){
        case 'cd' :
            info.dir = 'cd';
            break;
        case '_description':
            info.dir = 'cd.'+stateArray['cd'].value+'._description';
            break;
        case 'class':
            info.dir = 'class';
            //Name Reform
            //info.subType = 'className';
            info.subType = 'name';
            break;
        case 'className':
            //Name Reform
            //info.dir = 'class.'+stateArray['class'].id+'.className';
            info.dir = 'class.'+stateArray['class'].id+'.name';
            break;
        case 'attribute' :
            info.dir = 'class.'+stateArray['class'].id+'.attribute';
            //Name Reform
            //info.subType = 'attributeName';
            info.subType = 'name';
            break;
        case 'attributeName' :
            //Name Reform
            //info.dir = 'class.'+stateArray['class'].id+'.attribute.'+stateArray['attribute'].id+'.attributeName';
            info.dir = 'class.'+stateArray['class'].id+'.attribute.'+stateArray['attribute'].id+'.name';
            break;
        case 'attributeElem' :
            info.dir = 'class.'+stateArray['class'].id+'.attribute.'+stateArray['attribute'].id+'.'+stateArray['attributeElem'].type;
            break;
        case 'relation' :
            info.dir = 'relation';
            //Name Reform
            //info.subType = 'relationName';
            info.subType = 'name';
            break;
        case 'relationName':
            info.dir = 'relation.'+stateArray['relation'].id+'.name';
            break;
        case 'relationType' :
            info.dir = 'relation.'+stateArray['relation'].id+'.'+stateArray['relationType'].type;
            break;
        default : break;
    }
    return info;
};


IfmExchangeToCfm = function(process,collectionName,filter){
    switch(process){
        case 'remove':
            //此处对于subFilter的处理存在一定的问题，
            for(var i=0;i<relationList.length;i++){

            }
            var subFilterList = generateSubFilter(filter[1]);
            var subFilter = {};
            for(var i=0;i<subFilterList.length;i++){
                subFilter[subFilterList[i]] = -1;
            }
            console.log(subFilter);
            cfm.ref(collectionName,filter[0],subFilter,function(err,number){
            });
            break;
    }
}

generateSubFilter = function generateSubFilter(sub){
    var subFilter=[];
    var preFilter="";
    generateFilter(sub,preFilter,subFilter);
    return subFilter;
};

generateFilter = function(sub,preFilter,subFilter){
    if(typeof sub === 'string') return;
    for(var key in sub){
        if(key === '_nor'){
            subFilter[subFilter.length] = preFilter+key
        }
        else{
            generateFilter(sub[key],preFilter+key+".",subFilter);
        }
    }
};

relationExchangeIntoOperation = function(relationType,sourceType){
    var elementType;
    switch(relationType){
        case 'is-a':
            elementType = sourceType;
            break;
        case 'deserve':
            elementType = 'property';
            break;
        case 'initiate':
            elementType = 'threat';
            break;
        case 'target':
            elementType = 'entity';
        case 'dealwith':
            elementType = 'threat';
            break;
        case 'generate':
            elementType = 'impact';
            break;
        case 'jeopardize':
            elementType = 'property';
            break;
    }
    return elementType;
}